<template>
  <div class="video-preview">
    <el-card shadow="never">
      <div class="preview">
        <div>
          <div class="video-box">
            <div class="cursor" v-if="file" :style="{ left: `${mouseX}px` }"></div>
            <video v-if="file" ref="preview" @contextmenu.prevent="" @mousemove="mm" @mouseout="mo">
              <source :src="file" type="video/mp4" />
            </video>
            <img class="preview-image" :src="localVal.cover" v-if="localVal.cover" />
          </div>
          <div class="video-box-btns">
            <!-- 不是上传或者上传完成 -->
            <el-button class="drag-btn" icon="el-icon-rank" v-if="canDrag">
              点我拖动
            </el-button>
            <el-button
              icon="el-icon-edit"
              type="success"
              v-if="localVal.videoId"
              v-permission="['course:video:check']"
              @click="$tabs.open({ name: 'VideoDetail', params: { id: localVal.videoId } })"
            >
              去精编
            </el-button>
            <!-- <el-button
              @click="$emit('abort')"
              type="primary"
              icon="el-icon-delete"
              v-if="localVal.status === 'uploading'"
            >
              停止上传
            </el-button>
            <el-button
              @click="$emit('resume')"
              type="success"
              icon="el-icon-delete"
              v-if="localVal.status === 'abort'"
            >
              继续上传
            </el-button> -->
            <el-button
              @click="$emit('remove')"
              type="danger"
              icon="el-icon-delete"
              v-permission="['course:video:del']"
            >
              移除
            </el-button>
            <el-button
              type="text"
              @click="window.open(`https://ke.movtile.com/video/${localVal.showVideoId}`, '_blank')"
              v-if="localVal.showVideoId"
            >
              去预览
            </el-button>
          </div>
        </div>
        <!-- TODO: 这个isVideo好像没用到 -->
        <div class="video-info">
          <el-form
            :model="localVal"
            ref="videoForm"
            :rules="isVideo ? singleVideoRule : videoRule"
            label-position="left"
            label-width="120px"
          >
            <el-form-item label="标题" prop="title">
              <el-input v-model.trim="localVal.title" @input="$emit('input', localVal)"></el-input>
            </el-form-item>
            <el-form-item label="简介(30字内)" prop="summary">
              <el-input
                v-model.trim="localVal.summary"
                maxlength="30"
                @input="$emit('input', localVal)"
              ></el-input>
            </el-form-item>
            <el-form-item label="讲师" prop="uuids">
              <el-select filterable v-model="localVal.uuids" @change="$emit('input', localVal)">
                <el-option
                  v-for="(t, index) in $teacherList"
                  :key="index"
                  :label="t.nickname"
                  :value="t.uuid"
                ></el-option>
              </el-select>
            </el-form-item>

            <template v-if="isVideo">
              <div>
                <el-form-item prop="payMode" label="视频付费类型">
                  <el-radio-group v-model="localVal.payMode">
                    <el-radio :label="1">VIP免费</el-radio>
                    <el-radio :label="2">VIP折扣</el-radio>
                    <el-radio :label="3">单点付费</el-radio>
                    <el-radio :label="0">免费</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item prop="payPrice" label="视频价格(元)">
                  <el-input-number
                    :controls="false"
                    :precision="2"
                    :step="0.01"
                    v-model="localVal.payPrice"
                    placeholder="最多精确到分"
                  ></el-input-number>
                </el-form-item>
                <el-form-item prop="showPrice" label="划线价格(元)">
                  <el-input-number
                    :controls="false"
                    :precision="2"
                    :step="0.01"
                    v-model="localVal.showPrice"
                    placeholder="最多精确到分"
                  ></el-input-number>
                </el-form-item>
                <el-form-item prop="categoryId" label="视频分类">
                  <el-cascader-panel
                    v-model="localVal.categoryId"
                    :options="$cateTree"
                    :props="{
                      value: 'id',
                      label: 'title',
                      children: 'childs',
                      emitPath: false,
                    }"
                  ></el-cascader-panel>
                </el-form-item>
              </div>
            </template>
            <el-form-item prop="showVideoId">视频ID : {{ localVal.showVideoId }}</el-form-item>
            <el-form-item label="添加素材" v-permission="['upload:resource:btn']">
              <upload-resource
                multiple
                use-file-name
                is-resource
                folder="cover"
                @upload="updateResource"
              ></upload-resource>
              <p style="color: #888;font-size:12px">*多组素材请打为zip压缩包</p>
              <el-tag
                effect="dark"
                :type="resource.id ? 'primary' : 'warning'"
                closable
                @close="delResource(index)"
                v-for="(resource, index) in localVal.resources"
                :key="index"
                style="margin-right: 5px"
              >
                {{ resource.filename }}
              </el-tag>
            </el-form-item>
          </el-form>

          <div v-if="value.status === 'done'">
            <i class="el-icon-success" style="color: #67C23A"></i>
            上传完成
          </div>
          <el-progress
            :percentage="value.percentage"
            v-if="['uploading', 'abort'].includes(localVal.status)"
          ></el-progress>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
  import UploadResource from 'comp/UploadResource';
  import { FormRuleConf } from '@/config';
  import { cloneDeep } from 'lodash';
  import { mapGetters } from 'vuex';

  export default {
    props: {
      value: {
        type: Object,
        default: () => {},
      },
      isVideo: {
        type: Boolean,
        default: false,
      },
      canDrag: {
        type: Boolean,
        default: true,
      },
    },
    data() {
      return {
        file: '',
        mouseX: 0,
        movePercent: 0,
        videoWidth: 0,
        confirmName: false,
        localVal: {},

        ...FormRuleConf.Video,
      };
    },
    components: {
      UploadResource,
    },
    watch: {
      value() {
        this.init();
      },
    },
    computed: {
      uploading() {
        return this.localVal.status === 'uploading';
      },
      ...mapGetters(['$teacherList', '$cateTree']),
    },
    mounted() {
      this.init();
      if (!this.localVal.title) {
        this.$set(this.localVal, 'title', this.localVal.name);
      }
    },
    methods: {
      /**
       * 初始化预览播放
       */
      init() {
        this.localVal = this.value;

        if (!this.localVal.resources) {
          this.$set(this.localVal, 'resources', []);
        }

        if (this.localVal.raw) {
          this.file = URL.createObjectURL(this.localVal.raw);
          this.$nextTick(() => {
            this.videoWidth = this.$refs.preview.getBoundingClientRect().width;
          });
        }
      },
      /**
       * 更新素材
       */
      updateResource(data) {
        // this.localVal.resources.push({
        //   filename: data.name,
        //   url: data.url,
        // });
        // 只保留一个
        this.localVal.resources = [
          {
            filename: data.name,
            url: data.url,
          },
        ];
      },
      /**
       * 删除素材
       */
      delResource(index) {
        const r = this.localVal.resources[index];
        if (r) {
          if (r.id) {
            this.$confirm('确认删除这个素材吗?', '提示').then(() => {
              this.$service
                .AssetResourceDelete({
                  resourceId: r.id,
                })
                .then(() => {
                  this.$set(
                    this.localVal,
                    'resources',
                    this.localVal.resources.filter((resource) => resource.id !== r.id),
                  );
                });
            });
          } else {
            this.localVal.resources.splice(index, 1);
            this.$set(this, 'localVal', this.localVal);
          }
        }
      },
      /**
       * Mousemove Event handler
       */
      mm(evt) {
        this.mouseX = evt.layerX;
        this.movePercent = (evt.layerX / this.videoWidth).toFixed(2);

        evt.target.currentTime = evt.target.duration * this.movePercent;
      },
      /**
       * MouseOut Event handler
       */
      mo(evt) {
        evt.target.currentTime = 0;
        this.mouseX = 0;
        this.movePercent = 0;
      },

      async valid() {
        this.updateValue();
        return await this.$refs.videoForm.validate();
      },

      updateValue() {
        this.$emit('input', this.localVal);
      },
    },
  };
</script>

<style lang="less" scoped>
  .video-preview {
    width: 100%;
    padding: 10px;
    position: relative;

    .el-icon-rank {
      width: 20px;
      height: 20px;
      background-color: #ccc;
      cursor: pointer;
      display: block;
      text-align: center;
      line-height: 20px;
      position: absolute;
      top: 10px;
      left: 10px;
      z-index: 1;
    }

    .preview {
      display: flex;
      padding-top: 5px;

      overflow: hidden;
      .order-increment;
    }

    & + .video-preview {
      margin-top: 10px;
    }
  }

  .video-box {
    position: relative;
    width: 200px;

    .preview-image {
      margin-bottom: 10px;
      border: 1px solid #ccc;
    }

    &-btns {
      display: flex;
      flex-direction: column;
      /deep/ .el-button {
        & + .el-button {
          margin-left: 0;
        }
        margin-bottom: 5px;
      }
    }

    .cursor {
      width: 2px;
      height: 100%;
      position: absolute;
      background-color: #ffc600;
      z-index: 1;
      pointer-events: none;
      display: none;
    }

    &:hover {
      .cursor {
        display: block;
      }
    }

    .el-progress {
      position: absolute;
      left: 0;
      right: 0;
    }

    video {
      width: 200px;
      height: 100px;
      object-fit: cover;
    }
  }

  .video-info {
    flex: 1;
    margin-left: 20px;
    min-width: 300px;
  }
</style>
